package org.zebra.mybatis.plus.ext.datapermission;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import org.dromara.streamquery.stream.plugin.mybatisplus.Database;
import org.springframework.context.event.ContextRefreshedEvent;
import org.zebra.mybatis.plus.ext.AnnotatedElementPlusUtil;
import org.zebra.mybatis.plus.ext.datapermission.annotation.DataPermission;
import org.zebra.mybatis.plus.util.MyBatisPlusUtil;

import java.util.List;

/**
 * 数据权限注册器
 * 主要是为了提升性能，避免每次都执行拦截器
 *
 * @author zhanghongbin
 */
public final class DataPermissionInterceptorRegister {

    private DataPermissionInterceptorRegister() {}

    public static boolean register(List<TableInfo> tableInfos, ContextRefreshedEvent contextRefreshedEvent) {
        boolean flag = false;
        for (TableInfo tableInfo : tableInfos) {
            Class<?> mapperClass = Database.getMapperClass(tableInfo.getEntityType());
            flag = Database.isDynamicMapper(mapperClass.getName());
            if (flag) continue;
            flag = AnnotatedElementPlusUtil.hasMethodAnnotation(mapperClass, DataPermission.class);
            if (flag) break;
        }
        if (flag) {
            MybatisPlusInterceptor mybatisPlusInterceptor =
                    contextRefreshedEvent.getApplicationContext().getBean(MybatisPlusInterceptor.class);
            if (mybatisPlusInterceptor != null) {
                DataPermissionInterceptor dataPermissionInterceptor =
                        new DataPermissionInterceptor(new DataPermissionHandlerImpl());
                MyBatisPlusUtil.addInterceptor(
                        mybatisPlusInterceptor,
                        dataPermissionInterceptor,
                        mybatisPlusInterceptor.getInterceptors().size() - 1);
            }
        }
        return flag;
    }
}
